package com.top10.service.impl;

import com.allinpay.ets.client.RequestOrder;
import com.allinpay.ets.client.SecurityUtil;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("tlfPayService")
public class TlfPayService {


	public void createPay(HttpServletRequest request, HttpServletResponse response) throws Exception {

	    //页面编码要与参数inputCharset一致，否则服务器收到参数值中的汉字为乱码而导致验证签名失败。
		request.setCharacterEncoding("UTF-8");

		String serverUrl = "https://cashier.allinpay.com/gateway/index.do";
		String key="#zKUjcZfRp$!2n9r";
		String version="v1.0";
		String language="1";
		String inputCharset= "1";
		String payType="0";
		String signType="1";
		String orderid="20180301671972";
		//商户号:
		String merchantId="009440353114150";
		//合作伙伴商户号
		String pid="";
        double money=1000.00;
		
//
//		User u=userService.selectById(userid);
//	if(u==null){
//			return;
//		}
		//临时处理
		//u.setPayuserid("180501895160398");
		
//		if(u.getPayuserid()==null || u.getPayuserid().equals("")){
//
//
//			logger.info("--------------------------------------创建订单支付！-------------支付userid ------------不存在--------------------------------");
//
//			Map<String, String> params=new HashMap<String, String>();
//			params.put("key", key);
//			params.put("signType", signType);
//			params.put("merchantId", merchantId);
//			params.put("partnerUserId", u.getUuid()+u.getAccount());
//
//			//String json= HttpRequest.postData("https://cashier.allinpay.com/usercenter/merchant/UserInfo/reg.do",params,"UTF-8");
//
//			//allinpayRegister(merchantId,u.getUuid()+u.getAccount());
//
//
//			String result = SunMd5.TextRegister(merchantId, u.getUuid()+u.getAccount(),
//					key);
//
//
//
//			u.setPayuserid(result);
//			userService.updateByPrimaryKeySelective(u);
//		}else{
//			logger.info("--------------------------------------创建订单支付！-------------支付userid存在："+u.getPayuserid()+"--------------------------------");
//		}

		//回调地址
		//String receiveUrl="https://my.t10mall.com/tlfpay/receive.do";
		String receiveUrl="https://www.baidu.com/";
		
		//回调地址
		//String pickupUrl="https://my.t10mall.com/tlfpay/SyncNotifyAction.do";
		String pickupUrl="https://www.baidu.com/";
		//订单
		String orderNo=orderid;
		//订单金额(单位分):
		
		 Double dou_obj = new Double(money*100);
	        NumberFormat nf = NumberFormat.getInstance();
	        nf.setGroupingUsed(false);
	        String dou_str = nf.format(dou_obj);
		
		String orderAmount=dou_str;
		//用于计算signMsg的key值:
		String sign="";		
		
		
		 Date newTime = new Date();  
	        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddhhmmss");  
	        String formatDate = dateFormatter.format(newTime);  
		
		//20180430201602
		String orderDatetime=formatDate;

		
		String orderCurrency="0";
		
		//订单过期时间:
		String orderExpireDatetime="60";
		
		String payerTelephone="";
		String payerEmail="";
		String payerName="";
		String payerIDCard="";
	
		String productName="TOP10 MALL";
		String productId="";
		String productNum="1";
		String productPrice="";
		String productDesc="";
		String ext1="<USER>"+"180501895160398"+"</USER>";
		String ext2="";
		String extTL="";//通联商户拓展业务字段，在v2.2.0版本之后才使用到的，用于开通分账等业务
		String issuerId="";
		String pan="";
		String tradeNature ="GOODS";
		

		//若直连telpshx渠道，payerTelephone、payerName、payerIDCard、pan四个字段不可为空
		//其中payerIDCard、pan需使用公钥加密（PKCS1格式）后进行Base64编码
		if(null!=payerIDCard&&!"".equals(payerIDCard)){
			try{
				//payerIDCard = SecurityUtil.encryptByPublicKey("C:\\TLCert.cer", payerIDCard);
				payerIDCard = SecurityUtil.encryptByPublicKey("D:\\TLCert.cer", payerIDCard);
			
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		/*if(null!=pan&&!"".equals(pan)){
			try{
				pan = SecurityUtil.encryptByPublicKey("/cert/TLCert.cer", pan);
			}catch(Exception e){
				e.printStackTrace();
			}
		}*/
		
		//构造订单请求对象，生成signMg。
		RequestOrder requestOrder = new RequestOrder();
		if(null!=inputCharset&&!"".equals(inputCharset)){
			requestOrder.setInputCharset(Integer.parseInt(inputCharset));
		}
		requestOrder.setPickupUrl(pickupUrl);
		requestOrder.setReceiveUrl(receiveUrl);
		requestOrder.setVersion(version);
		if(null!=language&&!"".equals(language)){
			requestOrder.setLanguage(Integer.parseInt(language));
		}
		requestOrder.setSignType(Integer.parseInt(signType));
		requestOrder.setPayType(Integer.parseInt(payType));
		requestOrder.setIssuerId(issuerId);
		requestOrder.setMerchantId(merchantId);
		requestOrder.setPayerName(payerName);
		requestOrder.setPayerEmail(payerEmail);
		requestOrder.setPayerTelephone(payerTelephone);
		requestOrder.setPayerIDCard(payerIDCard);
		requestOrder.setPid(pid);
		requestOrder.setOrderNo(orderNo);
		requestOrder.setOrderAmount(Long.parseLong(orderAmount));
		requestOrder.setOrderCurrency(orderCurrency);
		requestOrder.setOrderDatetime(orderDatetime);
		requestOrder.setOrderExpireDatetime(orderExpireDatetime);
		requestOrder.setProductName(productName);
		if(null!=productPrice&&!"".equals(productPrice)){
			requestOrder.setProductPrice(Long.parseLong(productPrice));
		}
		if(null!=productNum&&!"".equals(productNum)){
			requestOrder.setProductNum(Integer.parseInt(productNum));
		}
		requestOrder.setProductId(productId);
		requestOrder.setProductDesc(productDesc);
		requestOrder.setExt1(ext1);
		requestOrder.setExt2(ext2);
		requestOrder.setExtTL(extTL);//通联商户拓展业务字段，在v2.2.0版本之后才使用到的，用于开通分账等业务
		requestOrder.setPan(pan);
		requestOrder.setTradeNature(tradeNature);
		requestOrder.setKey(key); //key为MD5密钥，密钥是在通联支付网关会员服务网站上设置。


		//String strSrcMsg = requestOrder.getSrc(); // 此方法用于debug，测试通过后可注释。
		String strSignMsg = requestOrder.doSign(); // 签名，设为signMsg字段值。

//		TreeMap<String,String> params = new TreeMap<String,String>();
//		params.put("cusid", SybConstants.SYB_CUSID);
//		params.put("appid", SybConstants.SYB_APPID);
//		params.put("version", "11");
//		params.put("trxamt", "1");
//		params.put("reqsn", String.valueOf(System.currentTimeMillis()));
//		params.put("paytype", "W01");
//		params.put("randomstr", SybUtil.getValidatecode(8));
//		params.put("body", "标题");
//		params.put("remark", "备注");
//		params.put("acct", "");
//		params.put("authcode", "123");
//		params.put("notify_url", "https://www.baidu.com/");
//		params.put("limit_pay", "");
//		String strSignMsg= SybUtil.sign(params,SybConstants.SYB_APPKEY);

		String html="<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body onLoad=\"document.zavfpay.submit();\" >"
				+ "<form  id=\"zavfpay\"  name=\"zavfpay\"  action=\""+serverUrl+"\" method=\"post\">"
				+ "<input type=\"hidden\" name=\"inputCharset\" value=\""+inputCharset+"\"/>"
				+ "<input type=\"hidden\" name=\"pickupUrl\" value=\""+pickupUrl+"\"/>"
				+ "<input type=\"hidden\" name=\"receiveUrl\" value=\""+receiveUrl+"\"/>"
				+ "<input type=\"hidden\" name=\"version\" value=\""+version +"\"/>"
				+ "<input type=\"hidden\" name=\"language\" value=\""+language +"\"/>"
				+ "<input type=\"hidden\" name=\"signType\" value=\""+signType+"\"/>"
				+ "<input type=\"hidden\" name=\"merchantId\" value=\""+merchantId+"\"/>"
				+ "<input type=\"hidden\" name=\"payerName\" value=\""+payerName+"\"/>"
				+ "<input type=\"hidden\" name=\"payerEmail\" value=\""+payerEmail+"\"/>"
				+ "<input type=\"hidden\" name=\"payerTelephone\" value=\""+payerTelephone +"\"/>"
				+ "<input type=\"hidden\" name=\"payerIDCard\" value=\""+payerIDCard +"\"/>"
				+ "<input type=\"hidden\" name=\"pid\" value=\""+pid+"\"/>"
				+ "<input type=\"hidden\" name=\"orderNo\" value=\""+orderNo+"\"/>"
				+ "<input type=\"hidden\" name=\"orderAmount\" value=\""+orderAmount +"\"/>"
				+ "<input type=\"hidden\" name=\"orderCurrency\" value=\""+orderCurrency+"\"/>"
				+ "<input type=\"hidden\" name=\"orderDatetime\" value=\""+orderDatetime+"\"/>"
				+ "<input type=\"hidden\" name=\"orderExpireDatetime\" value=\""+orderExpireDatetime +"\"/>"
				+ "<input type=\"hidden\" name=\"productName\" value=\""+productName+"\"/>"
				+ "<input type=\"hidden\" name=\"productPrice\" value=\""+productPrice+"\"/>"
				+ "<input type=\"hidden\" name=\"productNum\" value=\""+productNum +"\"/>"
				+ "<input type=\"hidden\" name=\"productId\" value=\""+productId+"\"/>"
				+ "<input type=\"hidden\" name=\"productDesc\" value=\""+productDesc+"\"/>"
				+ "<input type=\"hidden\" name=\"ext1\" value=\""+ext1+"\"/>"
				+ "<input type=\"hidden\" name=\"ext2\" value=\""+ext2+"\"/>"
				+ "<input type=\"hidden\" name=\"payType\" value=\""+payType+"\"/>"
				+ "<input type=\"hidden\" name=\"issuerId\" value=\""+issuerId+"\"/>"
				+ "<input type=\"hidden\" name=\"pan\" value=\""+pan +"\"/>"
				+ "<input type=\"hidden\" name=\"tradeNature\" value=\""+tradeNature +"\"/>"
				+ "<input type=\"hidden\" name=\"signMsg\" value=\""+strSignMsg +"\"/>"
				+ "<input type=\"submit\" value=\"commit order\"/>"
				+ "</form></body></html>";

		response.reset();
		       response.getOutputStream().println(html);
		response.getOutputStream().flush();
		response.getOutputStream().close();
	//	response.getWriter().println(html);
	}




	public  void print(Map<String, String> map){
		System.out.println("返回数据如下:");
		if(map!=null){
			for(String key:map.keySet()){
				System.out.println(key+";"+map.get(key));
			}
		}
	}
	
	
	
	
}
